package com.yike.common.tool;

import cn.hutool.core.io.IORuntimeException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.Charset;
import java.util.List;

@Slf4j
public class ZosClientUtil {

    private static final String BUCKET_NAME = "qyzj";
    //private static final String LOCATION = "cn-sh1";

    private ZosClientUtil() {

    }

    public static void uploadFile(File file) {
        // 创建ObsClient实例
        AmazonS3 obsClient = amazonS3Client;
        try {
            PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, file.getPath(), file);
            // 设置桶访问权限为私有读写，默认也是私有读写
            request.setCannedAcl(CannedAccessControlList.PublicRead);
            obsClient.putObject(request);
        } catch (RuntimeException e) {
            log.error("UpdateFile failed,message:{}", e.getMessage(), e);
        }
    }

    public static boolean uploadFile(String path, byte[] bytes) {
        log.debug("文件上传 path:{}", path);
        // 创建ObsClient实例
        AmazonS3 obsClient = amazonS3Client;
        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(bytes.length);
            PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, path, inputStream, metadata);
            // 设置桶访问权限为私有读写，默认是私有读写
            request.setCannedAcl(CannedAccessControlList.PublicRead);
            // 上传文件（byte数组）
            PutObjectResult result = obsClient.putObject(request);
            //todo: result.getETag()请求结果判断
            return true;
        } catch (RuntimeException | IOException e) {
            log.error("UpdateFile failed,message:{}", e.getMessage(), e);
        }
        return false;
    }

    public static void uploadFile(String path, File file) {
        // 创建ObsClient实例
        log.debug("文件上传 path:{},file length:{}", path, file.length());
        AmazonS3 obsClient = amazonS3Client;
        try {
            PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, path, file);
            // 设置桶访问权限为私有读写，默认是私有读写
            request.setCannedAcl(CannedAccessControlList.PublicRead);
            // 上传文件（byte数组）
            obsClient.putObject(request);
        } catch (RuntimeException e) {
            log.error("UpdateFile failed,message:{}", e.getMessage(), e);
        }
    }

    public static String downStream(String path) {
        AmazonS3 obsClient = amazonS3Client;
        if (!obsClient.doesObjectExist(BUCKET_NAME, path)) {
            return null;
        }
        S3Object obsObject = obsClient.getObject(BUCKET_NAME, path);
        try (InputStream input = obsObject.getObjectContent(); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            long len = obsObject.getObjectMetadata().getContentLength();

            if (len >= Integer.MAX_VALUE) {
                throw new IORuntimeException("File is larger then max array size");
            }
            byte[] b = new byte[(int) len];

            int readLen;
            while ((readLen = input.read(b)) != -1) {
                bos.write(b, 0, readLen);
            }
            return new String(bos.toByteArray(), Charset.forName("utf-8"));
        } catch (RuntimeException | IOException e) {
            log.error("downStream failed,message:{}", e.getMessage(), e);
        }
        return null;
    }

    public static boolean isExist(String path) {
        AmazonS3 obsClient = amazonS3Client;
        return obsClient.doesObjectExist(BUCKET_NAME, path);
    }

    public static List<S3ObjectSummary> listObjects(String path) {
        AmazonS3 obsClient = amazonS3Client;
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        listObjectsRequest.setBucketName(BUCKET_NAME);
        listObjectsRequest.setPrefix(path);
        ObjectListing result = obsClient.listObjects(listObjectsRequest);
        List<S3ObjectSummary> objectSummaries = result.getObjectSummaries();
        //去除路径文件
        objectSummaries.remove(0);
        return objectSummaries;
    }

    public static boolean deleteFile(String path) {
        AmazonS3 obsClient = amazonS3Client;
        try {
            // 删除单个对象
            obsClient.deleteObject(BUCKET_NAME, path);
            log.debug("deleteObject successfully path:{}", path);
            return true;
        } catch (RuntimeException e) {
            log.error("deleteObject failed message:{}", e.getMessage(), e);
        }
        return false;
    }

    private static AmazonS3 amazonS3Client;

    static {
        final String ACCESS_KEY = "WIL6HDIKZW55GAOKYJKB";
        final String SECRET_KEY = "eF6LKt53STqQAMDO1XCo75up38y9hkaQqdpIIcjL";
        final String END_POINT = "https://obs.cn-sh1.ctyun.cn";
        AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
        ClientConfiguration awsClientConfig = new ClientConfiguration();
        awsClientConfig.setSignerOverride("AWSS3V4SignerType");
        awsClientConfig.setProtocol(Protocol.HTTPS);
        amazonS3Client = AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withClientConfiguration(awsClientConfig)
                .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(END_POINT, ""))
                .disableChunkedEncoding()
                .enablePathStyleAccess()
                .build();
    }

}
